package com.changgou.order.service.impl;

import com.changgou.canal.goods.feign.SkuFeign;
import com.changgou.canal.goods.feign.SpuFeign;
import com.changgou.canal.goods.pojo.Sku;
import com.changgou.canal.goods.pojo.Spu;
import com.changgou.order.pojo.OrderItem;
import com.changgou.order.service.CartService;
import entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 秦川熙
 */
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SkuFeign skuFeign;

    @Autowired
    private SpuFeign spuFeign;

    /**
     * 添加购物车
     * @param num
     * @param id
     * @param username
     */
    @Override
    public void add(Integer num, Long id, String username) {
        //删除该商品的购物车数据， 如果传入的数量<=0，则删除该商品的购物车数据
        if (num <= 0) {
            redisTemplate.boundHashOps("Cart_" + username).delete(id);
            return ;
        }
        //查询SKU
        Result<Sku> resultSku = skuFeign.findById(id);
        if (resultSku != null && resultSku.isFlag()) {
            //获取sku
            Sku sku = resultSku.getData();
            //获取spu
            Result<Spu> resultSpu = spuFeign.findById(sku.getSpuId());

            //将sku转换成orderItem
            OrderItem orderItem = sku2orderItem(sku, resultSpu.getData(), num);

            /**
             * 购物车数据存入到Redis
             */
            redisTemplate.boundHashOps("Cart_" + username).put(id, orderItem);
        }
    }

    /**
     * 查询用户的购物车数据
     * @param username
     * @return
     */
    @Override
    public List<OrderItem> list(String username) {
        //查询所有购物车数据
        List<OrderItem> orderItems = redisTemplate.boundHashOps("Cart_" + username).values();
        return orderItems;
    }

    /**
     * SKU转成0rderItem
     * @param sku
     * @param spu
     * @param num
     * @return
     */
    private OrderItem sku2orderItem(Sku sku, Spu spu, Integer num) {
        OrderItem orderItem = new OrderItem();
        orderItem.setSpuId(sku.getSpuId());
        orderItem.setSkuId(sku.getId());
        orderItem.setName(sku.getName());
        orderItem.setPrice(sku.getPrice());
        orderItem.setNum(num);
        orderItem.setMoney(num * orderItem.getPrice());
        orderItem.setPayMoney(num * orderItem.getPrice());
        orderItem.setImage(sku.getImage());
        //重量 = 单个重量 * 数量
        orderItem.setWeight(sku.getWeight() * num);

        //分类ID设置
        orderItem.setCategoryId1(spu.getCategory1Id());
        orderItem.setCategoryId2(spu.getCategory2Id());
        orderItem.setCategoryId3(spu.getCategory3Id());

        return orderItem;
    }
}
